﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml.Linq;
using BTN04.DTO;
using BTN04.BUS;

namespace BTN04.USER
{
    public partial class giohang : System.Web.UI.Page
    {
       

        private bool IsPageRefresh = false;
        float tongtien = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            Panel1.Visible = false;
            if (!IsPostBack)
            {
                ViewState["postids"] = System.Guid.NewGuid().ToString();
                Session["postid"] = ViewState["postids"].ToString();
                LoadDS();
            }
            else
            {
                if (ViewState["postids"].ToString() != Session["postid"].ToString())
                {
                    IsPageRefresh = true;
                }
                Session["postid"] = System.Guid.NewGuid().ToString();
                ViewState["postids"] = Session["postid"];
            }

            ViewState["ReUrl"] = Request.UrlReferrer.ToString();
            if (Request.QueryString["idSanPham"] != null)
            {
                int masp = int.Parse(Request.QueryString["idSanPham"]);
                SanPhamDTO spDTO=new SanPhamDTO ();
                spDTO =SanPhamBUS .LaySanPhamTheoMa (masp );
                int soluong = CurrentContext.Cart.LaySoLuongTheoMa(masp);
                if (soluong < spDTO.SoLuongTon)
                {
                    CartItem cart = new CartItem(masp, 1);
                    CurrentContext.Cart.AddItem(cart);
                    (Master as Template.USER).HienThiSoLuong();
                }
                string url = ViewState["ReUrl"].ToString();
                Response.Redirect(url);
            }
            else
            {
                if (CurrentContext.Cart.Item.Count <= 0)
                {
                    btnUpdate.Visible = false;
                    btnHuy.Visible = false;
                    btnThanhToan.Visible = false;
                    lbTong.Visible = false;
                }
                
            }

        }

        public void LoadDS()
        {
            tongtien = 0;
            CurrentContext.Cart.XoaSanPham();
            gvGioHang.DataSource = CurrentContext.Cart.Item;
            gvGioHang.DataBind();
            (Master as Template.USER).HienThiSoLuong();
            lbTong.Text = "Tổng tiền: " + string.Format("{0:#,#.##}", tongtien) + " VNĐ";
        }


        //load danh sach hoa don
        public void DanhSachHoaDon()
        {
            NguoiDungBUS ndBUS = new NguoiDungBUS();
            NguoiDungDTO ndDTO = new NguoiDungDTO();
            string tendangnhap = Session["tendn"].ToString();
            ndDTO = ndBUS.LayThongTinNguoiDungTheoTenDangNhap(tendangnhap);
            ChiTietHoaDonBUS cthdBUS = new ChiTietHoaDonBUS();
            DataTable dt = new DataTable();
            dt = cthdBUS.LayChiTietHoaDonTheoMaNguoiDung(ndDTO.MaNguoiDung);
            DataTable dt1 = new DataTable();
            DataColumn c1 = dt1.Columns.Add("STT",Type.GetType("System.Int32"));
            DataColumn c2 = dt1.Columns.Add("TenSanPham", Type.GetType("System.String"));
            DataColumn c3 = dt1.Columns.Add("SoLuong", Type.GetType("System.Int32"));
            DataColumn c4 = dt1.Columns.Add("GiaBan", Type.GetType("System.Double"));
            DataColumn c5 = dt1.Columns.Add("ThanhTien", Type.GetType("System.Double"));
            for(int i=0;i<dt.Rows .Count ;i++)
            {
                int masp = Convert.ToInt32(dt.Rows [i]["MaSanPham"].ToString ());
                SanPhamDTO spDTO = new SanPhamDTO();
                spDTO = SanPhamBUS.LaySanPhamTheoMa(masp);
                DataRow r=dt1.NewRow();
                r[0]=(i+1).ToString ();
                r[1] = spDTO.TenSanPham.ToString ();
                int slmua=Convert .ToInt32 ( dt.Rows[i]["SoLuongMua"].ToString());
                r[2] =slmua.ToString ();
                r[3] = spDTO.GiaBan.ToString();
                float thanhtien = slmua * spDTO.GiaBan;
                r[4] = thanhtien.ToString();
                dt1.Rows.Add(r);
            }
            gvHoaDon .DataSource =dt1;
            gvHoaDon .DataBind ();
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (!IsPageRefresh)
            {
                foreach (GridViewRow row in gvGioHang.Rows)
                {
                    if (row.RowType == DataControlRowType.DataRow)
                    {
                        int masp = Convert.ToInt32(gvGioHang.DataKeys[row.RowIndex].Value);
                        SanPhamDTO spDTO = new SanPhamDTO();
                        spDTO = SanPhamBUS.LaySanPhamTheoMa(masp);
                        int sl = CurrentContext.Cart.LaySoLuongTheoMa(masp);
                        int soluong = 0;
                        if ((row.Cells[2].FindControl("txtSoLuong") as TextBox).Text != "")
                        {
                            soluong = Convert.ToInt32((row.Cells[2].FindControl("txtSoLuong") as TextBox).Text);
                            if (soluong+sl > spDTO.SoLuongTon)
                                soluong = spDTO.SoLuongTon;
                        }
                        CurrentContext.Cart.UpdateItem(masp, soluong);
                    }
                }
                LoadDS();
            }
        }

        protected void btnThanhToan_Click(object sender, EventArgs e)
        {
            Panel1.Visible = true;
            thanhtoan.Text = "HÓA ĐƠN CỦA BẠN";
            if (CurrentContext.Cart.Item.Count > 0)
            {
                HoaDonBUS hdBUS = new HoaDonBUS();
                ChiTietHoaDonBUS cthdBUS = new ChiTietHoaDonBUS();
                NguoiDungBUS ndBUS = new NguoiDungBUS();
                NguoiDungDTO ndDTO = new NguoiDungDTO();
                string tendangnhap = Session["tendn"].ToString();
                ndDTO = ndBUS.LayThongTinNguoiDungTheoTenDangNhap(tendangnhap );
                int mahd = 0;
                long tong = 0;
                for (int i = 0; i < CurrentContext.Cart.Item.Count; i++)
                {
                    HoaDonDTO hdDTO = new HoaDonDTO();
                    ChiTietHoaDonDTO cthdDTO = new ChiTietHoaDonDTO();
                    SanPhamDTO spDTO = new SanPhamDTO();
                    int masp = CurrentContext.Cart.Item[i].Masp;
                    spDTO = SanPhamBUS.LaySanPhamTheoMa(masp);
                    hdDTO.MaNguoiDung = ndDTO.MaNguoiDung;
                    hdDTO.ThoiGianMua = DateTime.Now;
                    hdDTO.MaTinhTrangHoaDon = 2;
                    mahd = hdBUS.ThemHoaDon(hdDTO );
                    if (mahd > 0)
                    {
                        ////////
                        cthdDTO.MaHoaDon = mahd;
                        cthdDTO.MaSanPham = spDTO.MaSanPham;
                        cthdDTO.MaNguoiDung = ndDTO.MaNguoiDung;
                        cthdDTO.SoLuongMua = CurrentContext.Cart.Item[i].SoLuong;
                        cthdDTO.GiaBan = spDTO.GiaBan;
                        cthdBUS.ThemChiTietHoaDon(cthdDTO);
                    }
                    tong += CurrentContext.Cart.Item[i].SoLuong * long.Parse (spDTO.GiaBan.ToString ());
                    SanPhamBUS spBUS = new SanPhamBUS();
                    spBUS.CapNhatSoLuongTon(masp, CurrentContext.Cart.Item[i].SoLuong);
                }
                lbtonghoadon.Text = "Tổng tiền: " + string.Format("{0:#,#.##}",tong)+" VNĐ";
                CurrentContext.Cart.HuyGioHang();
                DanhSachHoaDon();
                btnUpdate.Visible = false;
                btnHuy.Visible = false;
                btnThanhToan.Visible = false;
                lbTong.Visible = false;
                gvGioHang.Visible = false;
                hdBUS.CapNhatTinhTrangHoaDon(mahd, 1);
                (Master as Template.USER).HienThiSoLuong();
            }
        }

        protected void btnHuy_Click(object sender, EventArgs e)
        {
           
            CurrentContext.Cart.HuyGioHang();
            tongtien = 0;
            btnUpdate.Visible = false;
            btnHuy.Visible = false;
            btnThanhToan.Visible = false;
            lbTong.Visible = false;
            LoadDS();
        }

        protected void gvGioHang_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            SanPhamDTO spDTO = new SanPhamDTO();
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int masp = Convert.ToInt32(gvGioHang.DataKeys[e.Row.RowIndex].Value);
                spDTO = SanPhamBUS.LaySanPhamTheoMa(masp);
                e.Row.Cells[0].Text = spDTO.TenSanPham.ToString();
                e.Row.Cells[1].Text = string.Format("{0:#,#.##}", spDTO.GiaBan);
                int soluong =0;
                if((e.Row.Cells[2].FindControl("txtSoLuong") as TextBox).Text!="")
                    soluong = Convert.ToInt32((e.Row.Cells[2].FindControl("txtSoLuong") as TextBox).Text);
                float thanhtien = spDTO.GiaBan * soluong;
                e.Row.Cells[3].Text = string.Format("{0:#,#.##}", thanhtien)+" VNĐ";
                tongtien += thanhtien;
            }
        }

        protected void gvGioHang_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int masp = Convert.ToInt32(gvGioHang.DataKeys[e.RowIndex].Value);
            CurrentContext.Cart.RemoveItem(masp);
            if (CurrentContext.Cart.Item.Count <= 0)
            {
                tongtien = 0;
                btnUpdate.Visible = false;
                btnHuy.Visible = false;
                btnThanhToan.Visible = false;
                lbTong.Visible = false;
            }
            LoadDS();
        }

        protected void gvGioHang_DataBound(object sender, EventArgs e)
        {
            lbTong.Text = "Tổng tiền: " + string.Format("{0:#,#.##}", tongtien)+" VNĐ";
        }

        protected void gvHoaDon_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void gvHoaDon_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            NguoiDungBUS ndBUS = new NguoiDungBUS();
            NguoiDungDTO ndDTO = new NguoiDungDTO();
            string tendangnhap = Session["tendn"].ToString();
            ndDTO = ndBUS.LayThongTinNguoiDungTheoTenDangNhap(tendangnhap);
            ChiTietHoaDonBUS cthdBUS = new ChiTietHoaDonBUS();
            DataTable dt = new DataTable();
            dt = cthdBUS.LayChiTietHoaDonTheoMaNguoiDung(ndDTO.MaNguoiDung);
            DataTable dt1 = new DataTable();
            DataColumn c1 = dt1.Columns.Add("STT", Type.GetType("System.Int32"));
            DataColumn c2 = dt1.Columns.Add("TenSanPham", Type.GetType("System.String"));
            DataColumn c3 = dt1.Columns.Add("SoLuong", Type.GetType("System.Int32"));
            DataColumn c4 = dt1.Columns.Add("GiaBan", Type.GetType("System.Double"));
            DataColumn c5 = dt1.Columns.Add("ThanhTien", Type.GetType("System.Double"));
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                int masp = Convert.ToInt32(dt.Rows[i]["MaSanPham"].ToString());
                SanPhamDTO spDTO = new SanPhamDTO();
                spDTO = SanPhamBUS.LaySanPhamTheoMa(masp);
                DataRow r = dt1.NewRow();
                r[0] = (i + 1).ToString();
                r[1] = spDTO.TenSanPham.ToString();
                int slmua = Convert.ToInt32(dt.Rows[i]["SoLuongMua"].ToString());
                r[2] = slmua.ToString();
                r[3] = spDTO.GiaBan.ToString();
                float thanhtien = slmua * spDTO.GiaBan;
                r[4] = thanhtien.ToString();
                dt1.Rows.Add(r);
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                int stt = Convert.ToInt32(gvHoaDon.DataKeys[e.Row.RowIndex].Value);
                e.Row.Cells[0].Text = stt.ToString ();
                e.Row.Cells[1].Text = dt1 .Rows [stt -1]["TenSanPham"].ToString ();
                e.Row.Cells[2].Text = dt1.Rows[stt - 1]["SoLuong"].ToString();
                e.Row.Cells[3].Text = dt1.Rows[stt - 1]["GiaBan"].ToString();
                e.Row.Cells[4].Text = dt1.Rows[stt - 1]["ThanhTien"].ToString();
            }
        }

        protected void gvGioHang_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvGioHang.PageIndex = e.NewPageIndex;
            LoadDS();
        }

        protected void gvHoaDon_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvHoaDon.PageIndex = e.NewPageIndex;
            DanhSachHoaDon();
        }

    
    }
}
